﻿using Castle.Core.Logging;
using com.ytocargo.Application.BackgroundJobInfos;
using com.ytocargo.Application.BackgroundJobs;
using com.ytocargo.Application.FlightInfos;
using com.ytocargo.Core.BackgroundJobInfos;
using com.ytocargo.Core.FlightInfo4Monitors;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Yto.Common.Dependency;
using Yto.Common.Extensions;
using Yto.Threading;
using Yto.Threading.BackgroundWorkers;
using Yto.Unitwork;

namespace com.ytocargo.Application.FlightInfo4Monitors
{
    public class SendFltInfo4MPeriod : TimedBgdWorker, ISendFltInfo4MPeriod, ISingleton
    {
        private readonly ICtnManager _ctnManager;
        private ILogger _logger;
        private readonly IFlightInfo4MonitorServices _flightInfo4MonitorServices;
        private readonly IBackgroundJobInfoServices _backgroundJobInfoServices;
        private readonly IBackgroundJobManager _jobManager;
        private IUnitManager _unitManager;

        public SendFltInfo4MPeriod(BaseTimer baseTimer,
            ICtnManager ctnManager,
            IFlightInfo4MonitorServices flightInfo4MonitorServices,
            IBackgroundJobInfoServices backgroundJobInfoServices,
            IBackgroundJobManager jobManager,
            IUnitManager unitManager)
            : base(baseTimer)
        {
            JobPeriod = int.TryParse(ConfigurationManager.AppSettings["MqSendPeriod"], out int tempValue)
                        ? tempValue : 20000;

            baseTimer.Period = JobPeriod;

            _ctnManager = ctnManager;
            _logger = _ctnManager.IsRegisted<ILoggerFactory>() ?
                _ctnManager.Resolver<ILoggerFactory>().Create(typeof(SendFltInfo4MPeriod))
                : NullLogger.Instance;
            _flightInfo4MonitorServices = flightInfo4MonitorServices;
            _backgroundJobInfoServices = backgroundJobInfoServices;
            _jobManager = jobManager;
            _unitManager = unitManager;

        }
        protected async override void DoWork()
        {
            var count = await _backgroundJobInfoServices.CountTodayJobbyJobType(typeof(SendFlightInfo4MWorker));
            if (count == 0)
            {
                var today = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                await _jobManager.EnqueueAsync<SendFlightInfo4MWorker, SendFlightInfo4MArgs>(
                            new SendFlightInfo4MArgs(), today
                            );
            }
            else
            {
                await _backgroundJobInfoServices.CheckTodayJobByJobType(typeof(SendFlightInfo4MWorker));
            }

            using (var uw = _unitManager.Begin())
            {
                var filter = new FlightInfoFilter();
                filter.FlightDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());

                var list = _flightInfo4MonitorServices.GetListByMap(filter);
                var modifyList = new List<FlightInfo4Monitor>();
                list.ForEach(x =>
                {
                    if (!_flightInfo4MonitorServices.QueryByEntity(x).Result)
                    {
                        modifyList.Add(x);
                    }
                });

                var delList = _flightInfo4MonitorServices.GetDeleteList();
                delList.ForEach(x =>
                {
                    x.FltStatus = "Z";
                });
                modifyList.AddRange(delList);

                if (modifyList.Count > 0)
                {
                    MqHelper.SendMq("AirLines_FlightDynamic", "CAST.HYT.FlightDynamic", modifyList.ToJsonString(), _logger);
                }

                modifyList.ForEach(x =>
                {
                    _flightInfo4MonitorServices.UpdateOrInsert(x);
                });
                uw.Complete();
            }
        }

        public int JobPeriod { get; private set; }
    }
}
